const express = require('express');
const router = express.Router();

const BugComment = require('../models/BugComment');

const { authMiddleware } = require('../middleware/auth');
const CODE = require('../constants/code');
const { logOperation } = require('../utils/log');

// 添加 Bug 评论
router.post('/add', authMiddleware,async (req, res) => {
    console.log("添加Bug评论");
    
    try {
        const { 
            bugId,        // 要评论的 Bug 的唯一标识符
            content,      // 评论的文本内容
            commentType = 'comment' // 评论类型（如未指定，默认为 'comment'）
         } = req.body;
        const userId = req.user.userId;

        const commentId = await BugComment.addComment(bugId, userId, content, commentType);

        // 记录操作日志
        await logOperation(
            {
                userId: userId,
                type: 'create',
                module: 'Bug评论',
                details: `为Bug ${bugId} 添加评论`,
                ip: req.ip,
                userAgent: req.headers['user-agent']
            }
            // userId,
            // 'create',
            // 'Bug评论',
            // `为Bug ${bugId} 添加评论`,
            // req.ip,
            // req.headers['user-agent']
        );

        res.json({
            code: CODE.SUCCESS,
            message: '添加Bug评论成功',
            data: { commentId }
        });
    } catch (error) {
        console.error('添加Bug评论错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 获取特定 Bug 的所有评论
router.get('/list/:bugId', authMiddleware, async (req, res) => {
    try {
        const { bugId,page = 1, pageSize = 10 } = req.query;

        const result = await BugComment.getCommentsByBugIdWithPage(
            bugId, 
            parseInt(page), 
            parseInt(pageSize)
        );

        res.json({
            code: CODE.SUCCESS,
            message: '获取Bug评论成功',
            data: result
        });
    } catch (error) {
        console.error('获取Bug评论错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 获取单个评论详情
router.get('/detail', authMiddleware, async (req, res) => {
    try {
        const { commentId } = req.query;

        const commentDetail = await BugComment.getCommentDetail(commentId);

        if (!commentDetail) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '评论不存在'
            });
        }

        res.json({
            code: CODE.SUCCESS,
            message: '获取评论详情成功',
            data: commentDetail
        });
    } catch (error) {
        console.error('获取评论详情错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 更新 Bug 评论
router.put('/update', authMiddleware, async (req, res) => {
    try {
        const { content,commentId } = req.body;
        const userId = req.user.id;

        const success = await BugComment.updateComment(commentId, content);

        if (!success) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '评论不存在或无权修改'
            });
        }

        // 记录操作日志
        await logOperation(
            {
                userId: userId,
                type: 'update',
                module: 'Bug评论',
                details: `更新Bug评论 ${commentId}`,
                ip: req.ip,
                userAgent: req.headers['user-agent']
            }
        );

        res.json({
            code: CODE.SUCCESS,
            message: '更新Bug评论成功'
        });
    } catch (error) {
        console.error('更新Bug评论错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

// 删除 Bug 评论
router.delete('/delete', authMiddleware, async (req, res) => {
    try {
        const { commentId} = req.query;
        const userId = req.user.userId;

        const success = await BugComment.deleteComment(commentId);

        if (!success) {
            return res.json({
                code: CODE.NOT_FOUND,
                message: '评论不存在或无权删除'
            });
        }

        // 记录操作日志
        await logOperation(
            {
                userId: userId,
                type: 'delete',
                module: 'Bug评论',
                details: `删除Bug评论 ${commentId}`,
                ip: req.ip,
                userAgent: req.headers['user-agent']
            }
        );

        res.json({
            code: CODE.SUCCESS,
            message: '删除Bug评论成功'
        });
    } catch (error) {
        console.error('删除Bug评论错误:', error);
        res.status(500).json({
            code: CODE.SERVER_ERROR,
            message: '服务器错误'
        });
    }
});

module.exports = router;
